mod utils;

use std::fs::File;
use std::io::{self, BufReader, Read, Write};
use std::path::Path;
use crate::utils::invoke_repair_json;

pub fn repair_json(json_str: &str) -> Result<String, anyhow::Error>  {
     let repaired_str = invoke_repair_json(json_str ).unwrap();
    Ok(repaired_str)
}

// 从文件读取并修复 JSON 的函数
pub fn from_file_repair_json(
    filename: &Path,
) ->  Result<String, io::Error>{
    let file = File::open(filename)?;
    let mut buf_reader = BufReader::new(file);
    let mut json_str = String::new();
    buf_reader.read_to_string(&mut json_str)?;


    // 调用 repair_json 函数
    let json_string = repair_json(&*json_str )
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

    Ok(json_string.to_string())
}




pub fn repair_and_save_to_file(filename: &Path) {
        let json_string = from_file_repair_json(filename).unwrap();
     //  let     mut chars  : Vec<char>  = json_string.chars().collect();
     //  let  len = chars.len();
     //      chars[0] = '{';
     //      chars[len-1] = '}';
     // let result = String::from_iter(chars);
        let mut file = File::create(filename).unwrap();
        file.write_all(json_string.as_bytes()).unwrap();
        println!("JSON file {} has been repaired and saved to file", filename.display());
}

